#include "sdiffengine.h"

/* kills program while printing terminating message */
void die(const char *errstr, ...) {
    va_list ap;

    va_start(ap, errstr);
    vfprintf(stderr, errstr, ap);
    va_end(ap);
    exit(1);
}

/* prints usage string before exiting */
void usage(void) {
    die("usage: sdiffengine [-vb] [-f file] [-n continuation]\n"
        "       -f ... reads from stdin if not specified\n"
        "       -n ... total n desired sequence numbers\n"
        "              set to 1 if not specified\n"
        "       -b ... verbose output\n"
        "       -v ... print version\n");
}

/* perhaps self-explanatory */
int main(int argc, char **argv) {

    /* arg parsing */
    ARGBEGIN {
    case 'f':
        opt_file = EARGF(usage());
        break;
    case 'n':
        opt_size = EARGF(usage());
        break;
    case 'b':
        opt_verb = VERBOSE;
        break;
    case 'h':
        usage();
    case 'v':
        die("sdiffengine 2nd edition v2.31 (c) 2019 strlst\n");
        break;
    } ARGEND;

    /* read from specified file */
    FILE *in = stdin;
    if (opt_file != NULL)
        in = fopen(opt_file, "r");
    /* signal error in case of error */
    if (in == NULL)
        die("sdiffengine: could not open '%s': no such file or directory\n", opt_file);

    size_t n = 1;
    if (opt_size)
        n = strtol(opt_size, NULL, 10);

    /* generate root sequence */
    diff_layer *root = gen_initial_seq(in);

    /* close read file */
    if (opt_file != NULL)
        fclose(in);

    /* verbose output for the verbose */
    verbose("\ndebugging seq tree:\n");
    verbose(" ");
    print_diff_layer(root);

    /* generate subsequent diffs */
    int ret = gen_all_diffs(root);

    /* continue seq until n */
    if (ret == SOLUTION_FOUND) {
        gen_next_n(root, root->size + n);
        print_diff_layer_seq(root);
    } else {
        printf("no solution found\n");
    }

    /* holy grail of memory management */
    destroy_diff_layer(root);

    return 0;
}
